package com.nlp.shop.web.beetl;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.beetl.core.Format;

public class DateFormat implements Format {

	@Override
	public Object format(Object data, String pattern) {
		if (data == null)
			return null;
		if (Date.class.isAssignableFrom(data.getClass())) {
			SimpleDateFormat sdf = null;
			if (pattern == null) {
				sdf = new SimpleDateFormat();
			} else {
				sdf = new SimpleDateFormat(pattern);
			}
			return sdf.format((Date) data);

		} else if (Long.class.isAssignableFrom(data.getClass())) {
			Date date = null;
			if (lengthOfLong((Long) data) > 10) {
				date = new Date((Long) data);
			} else {
				date = new Date((Long) data * 1000);
			}
			
			SimpleDateFormat sdf = null;
			if (pattern == null) {
				sdf = new SimpleDateFormat();
			} else {
				sdf = new SimpleDateFormat(pattern);
			}
			return sdf.format(date);
		}
		
		else {
			throw new RuntimeException("Arg Error:Type should be Date");
		}
	}
	
	/**
	 * 
	 * 计算Long数字的字母数
	 *
	 * @param num
	 * @return
	 */
	private static int lengthOfLong(Long num) {
		if (num == null) {
			return 0;
		}
		String str = String.valueOf(num);
		return str.length();
	}

}
